package com.flycms.modules.user.service.impl;

import com.flycms.common.pager.Pager;
import com.flycms.common.utils.bcrypt.BCrypt;
import com.flycms.common.utils.bcrypt.BCryptPasswordEncoder;
import com.flycms.common.utils.mark.SnowFlakeUtils;
import com.flycms.common.utils.result.LayResult;
import com.flycms.common.utils.result.Result;
import com.flycms.modules.user.dao.AdminDao;
import com.flycms.modules.user.dao.AdminRoleMergeDao;
import com.flycms.modules.user.entity.Admin;
import com.flycms.modules.user.entity.AdminRoleMerge;
import com.flycms.modules.user.entity.AdminVo;
import com.flycms.modules.user.service.AdminService;
import com.flycms.modules.shiro.ShiroUtils;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Open source house, All rights reserved
 * 版权：28844.com<br/>
 * 开发公司：28844.com<br/>
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email 79678111@qq.com
 * @Date: 11:19 2019/8/18
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private AdminRoleMergeDao adminRoleMergeDao;

    // ///////////////////////////////
    // /////       增加       ////////
    // ///////////////////////////////

    @Transactional
    public Result addAdmin(Admin admin) {

        if (admin == null) {
            return Result.failure("未登录或未获取到用户信息");
        }
        if(this.checkByUserName(admin.getUserName(),null)){
            return Result.failure("用户名已存在");
        }
        admin.setId(SnowFlakeUtils.nextId());
        admin.setPassword(new BCryptPasswordEncoder().encode(admin.getPassword()));
        admin.setCreateTime(LocalDateTime.now());
        adminDao.save(admin);

        for(int i=0,size = admin.getRoleId().length; i < size;i++)
        {
            //roleid不等于空，必须是数字，没有验证角色id是否存在
            if(admin.getRoleId()[i]!=null || NumberUtils.isNumber(admin.getRoleId()[i].toString())){
                AdminRoleMerge merge=new AdminRoleMerge();
                merge.setId(SnowFlakeUtils.nextId());
                merge.setUserId(admin.getId());
                merge.setRoleId(admin.getRoleId()[i]);
                adminRoleMergeDao.save(merge);
            }
        }
        return  Result.success("管理员添加成功");
    }
    // ///////////////////////////////
    // /////        刪除      ////////
    // ///////////////////////////////

    // ///////////////////////////////
    // /////        修改      ////////
    // ///////////////////////////////
    /**
     * 用户修改密码
     *
     * @param oldPassword
     *        旧密码
     * @param password
     *        新密码
     * @throws Exception
     */
    @CacheEvict(value = "user", allEntries = true)
    @Transactional
    public Result updatePassword(String oldPassword, String password) {
        Long userId = ShiroUtils.getLoginUser().getId();
        Admin user = adminDao.findById(userId);
        if (user == null) {
            return Result.failure("未登录或未获取到用户信息！");
        }
        if (BCrypt.checkpw(oldPassword, user.getPassword())) {
            String pwHash = BCrypt.hashpw(password, BCrypt.gensalt());
            adminDao.updatePassword(pwHash,userId);
        } else {
            return  Result.failure("原始密码错误");
        }
        return  Result.success("密码已修改","/admin/user/password.do");
    }


    // ///////////////////////////////
    // /////        查詢      ////////
    // ///////////////////////////////

    /**
     * 排除当前用户id后查询用户名是否存在,如果userId设置为null则查全部的用户名
     *
     * @param userName
     *         用户登录手机号码
     * @param id
     *         需要排除的用户id,可设置为null
     * @return
     */
    public boolean checkByUserName(String userName,Long id) {
        int totalCount = adminDao.checkByUserName(userName,id);
        return totalCount > 0 ? true : false;
    }

    /**
     * 按用户名id查询用户注册信息
     *
     * @param userId
     * @return
     */
    public Admin findById(Long userId) {
        return adminDao.findById(userId);
    }

    /**
     * 通过username查询用户信息
     *
     * @param userName
     * @return User
     */
    @Cacheable(value = "user")
    public Admin findByUsername(String userName) {
        return adminDao.findByUsername(userName);
    }


    /**
     * 翻页列表
     *
     * @param userName
     *         根据分类名查询
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    public Object selectUserListPager(String userName, Integer page, Integer limit, String sort, String order) {
        //javabean 映射工具
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        MapperFacade mapper = mapperFactory.getMapperFacade();

        StringBuffer whereStr = new StringBuffer(" 1 = 1");
        if (!StringUtils.isEmpty(userName)) {
            whereStr.append(" and user_name like concat('%',#{entity.userName},'%')");
        }
        whereStr.append(" and deleted = 0");

        Pager<Admin> pager = new Pager(page, limit);
        //排序设置
        if (!StringUtils.isEmpty(sort)) {
            Boolean rank = "desc".equals(order) ? true : false;
            pager.addOrderProperty(sort, rank,true);
        }
        //使用limit进行查询翻页
        pager.addLimitProperty(true);
        //查询条件
        Admin user = new Admin();
        user.setUserName(userName);
        pager.setEntity(user);

        pager.setWhereStr(whereStr.toString());
        List<Admin> adminList=adminDao.queryList(pager);
        //BeanMapper.mapList(adminList,AdminVo.class);
        return LayResult.success(0, "true", adminDao.queryTotal(pager), mapper.mapAsList(adminList,AdminVo.class));
    }
}
